package com.tjetc.controller;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tjetc.common.Result;
import com.tjetc.domain.*;
import com.tjetc.service.*;
import com.tjetc.service.impl.*;
import com.tjetc.utils.JwtUtil;
import com.tjetc.utils.PageInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.lang.reflect.Method;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.TextStyle;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

@WebServlet("/nurse/*")
@MultipartConfig(location = "D:\\yiyuanphoto")
public class NurseServlet extends HttpServlet {
    private NurseService nurseService=new NurseServiceImpl();
    private DepartmentService departmentService=new DepartmentServiceImpl();
    private NclassesService nclassesService=new NclassesServiceImpl();
    private DoctorService doctorService = new DoctorServiceImpl();
    private RecordService recordService = new RecordServiceImpl();
    private NotesService notesService=new NotesServiceImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);
        try {
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void listNurByDepid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer depid = Integer.valueOf(request.getParameter("depid"));
        List<Nurse> nurses = nurseService.queryByDepid(depid);
        new ObjectMapper().writeValue(response.getOutputStream(),nurses);
    }

    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Nurse nurse = nurseService.login(username,password);
        String token= JwtUtil.createToken(username);
        if (nurse==null){
            new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("用户名/密码错误"));
        }
        new ObjectMapper().writeValue(response.getOutputStream(), Result.success(token,"登录成功"));
    }

    protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String curPage = request.getParameter("curPage");
        String ps = request.getParameter("pageSize");
        name=name==null?"":name;
        //接受请求参数
        //空处理:赋值给当前页码
        int currentPage = curPage == null ? 1:Integer.valueOf(curPage);
        //每页显示的条数
        int pageSize = ps == null ? 5 : Integer.parseInt(ps);
        //总记录数
        int count = nurseService.getCount(name);
        PageInfo<Nurse> pageInfo = new PageInfo<>(currentPage, count, pageSize);
        List<Nurse> list=nurseService.list(name,pageInfo);
        pageInfo.setList(list);
        System.out.println("护士信息 = " + list);
        new ObjectMapper().writeValue(response.getOutputStream(),pageInfo);
    }

    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username=request.getParameter("username");
        int age=Integer.valueOf(request.getParameter("age"));
        String sex=request.getParameter("sex");
        String phone=request.getParameter("phone");
        int depid= Integer.valueOf(request.getParameter("depid"));
        Part part=request.getPart("photo");
        Nurse nurse=new Nurse();
        nurse.setUsername(username);
        nurse.setAge(age);
        nurse.setSex(sex);
        nurse.setPhone(phone);
        nurse.setDepid(depid);
        if (part!=null&&part.getSize()>0){
            String fn = part.getSubmittedFileName();
            String extName = fn.substring(fn.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString()+extName;
            part.write(fileName);
            nurse.setAvatar("upload/"+fileName);
        }
        Nurse nurse1=nurseService.getByName(username);
        if (nurse1!=null){
            new ObjectMapper().writeValue(response.getOutputStream(),Result.fail("用户名重复"));
        }
        else{
            boolean b = nurseService.add(nurse);
            if (b){
                new ObjectMapper().writeValue(response.getOutputStream(), Result.success("添加成功"));
            }
            new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("添加失败，出异常喽！"));
        }


    }

    protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id= Integer.parseInt(request.getParameter("id"));
        Nurse oldNurse=nurseService.getById(id);
        String username=request.getParameter("username");
        int age=Integer.valueOf(request.getParameter("age"));
        String sex=request.getParameter("sex");
        String phone=request.getParameter("phone");
        int depid= Integer.valueOf(request.getParameter("depid"));
        Part part=request.getPart("photo");
        System.out.println("part = " + part);
        Nurse nurse=new Nurse();
        nurse.setId(id);
        nurse.setUsername(username);
        nurse.setAge(age);
        nurse.setSex(sex);
        nurse.setPhone(phone);
        nurse.setDepid(depid);
        if (part!=null&&part.getSize()>0 &&part.getSubmittedFileName()!=null){
            String fn = part.getSubmittedFileName();
            String extName = fn.substring(fn.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString()+extName;
            part.write(fileName);
            nurse.setAvatar("upload/"+fileName);
        }else{
            nurse.setAvatar(oldNurse.getAvatar());
        }
        boolean b = nurseService.update(nurse);
        if (b){
            new ObjectMapper().writeValue(response.getOutputStream(), Result.success("修改成功"));
        }
        new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("修改失败"));
    }

    protected void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id= Integer.parseInt(request.getParameter("id"));
        Notes notes=notesService.findByNid(id);
        if (notes==null){
            boolean b=nurseService.del(id);
            if (b){
                new ObjectMapper().writeValue(response.getOutputStream(), Result.success("删除成功"));
            }
            new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("删除失败"));
        }else{
            new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("删除失败,当前护士不能被删除"));
        }

    }

    protected void listByDepid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer rid = Integer.valueOf(request.getParameter("rid"));
        Record record = recordService.getById(rid);
        int depid = doctorService.getDepidById(record.getDid());
        List<Nurse> nurses = nurseService.queryByDepid(depid);
        new ObjectMapper().writeValue(response.getOutputStream(),nurses);
    }

    protected void findPasswordById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id= Integer.parseInt(request.getParameter("id"));
        Nurse nurse=nurseService.getpwdById(id);
        String password=nurse.getPassword();
        new ObjectMapper().writeValue(response.getOutputStream(),password);
    }

    protected void updatepwd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id= Integer.parseInt(request.getParameter("id"));
        String password=request.getParameter("newPassword");
        Nurse nurse=new Nurse();
        nurse.setId(id);
        nurse.setPassword(password);
        boolean b=nurseService.updatepwd(nurse);
        if (b){
            new ObjectMapper().writeValue(response.getOutputStream(), Result.success("修改成功"));
        }
        new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("修改失败"));


    }
    protected void info(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        Nurse nurse = nurseService.findByName(username);
        new ObjectMapper().writeValue(response.getOutputStream(), Result.success(nurse));
    }


    protected void qiandao(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //护士id
        int id= Integer.parseInt(request.getParameter("id"));
        System.out.println("id = " + id);
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 获取今天的星期
        DayOfWeek dayOfWeek = today.getDayOfWeek();
        // 获取星期的本地化名称
        String dayOfWeekName = dayOfWeek.getDisplayName(TextStyle.FULL, Locale.getDefault());
        if (dayOfWeekName.equals("星期一")){
            dayOfWeekName="周一";
        }else if (dayOfWeekName.equals("星期二")){
            dayOfWeekName="周二";
        }
        else if (dayOfWeekName.equals("星期三")){
            dayOfWeekName="周三";
        }
        else if (dayOfWeekName.equals("星期四")){
            dayOfWeekName="周四";
        }
        else if (dayOfWeekName.equals("星期五")){
            dayOfWeekName="周五";
        }
        else if (dayOfWeekName.equals("星期六")){
            dayOfWeekName="周六";
        }
        else if (dayOfWeekName.equals("星期日")){
            dayOfWeekName="周日";
        }
        Nclasses nclasses=nclassesService.findByIdandDate(id,dayOfWeekName);
        System.out.println("nclasses = " + nclasses);
        new ObjectMapper().writeValue(response.getOutputStream(), nclasses);
    }

    protected void sureqiandao(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //医生id
        int id= Integer.parseInt(request.getParameter("id"));
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 获取今天的星期
        DayOfWeek dayOfWeek = today.getDayOfWeek();
        // 获取星期的本地化名称
        String dayOfWeekName = dayOfWeek.getDisplayName(TextStyle.FULL, Locale.getDefault());
        if (dayOfWeekName.equals("星期一")){
            dayOfWeekName="周一";
        }else if (dayOfWeekName.equals("星期二")){
            dayOfWeekName="周二";
        }
        else if (dayOfWeekName.equals("星期三")){
            dayOfWeekName="周三";
        }
        else if (dayOfWeekName.equals("星期四")){
            dayOfWeekName="周四";
        }
        else if (dayOfWeekName.equals("星期五")){
            dayOfWeekName="周五";
        }
        else if (dayOfWeekName.equals("星期六")){
            dayOfWeekName="周六";
        }
        else if (dayOfWeekName.equals("星期日")){
            dayOfWeekName="周日";
        }
        //System.out.println("dayOfWeekName = " + dayOfWeekName);
        Nclasses nclasses1=nclassesService.findByIdandDate(id,dayOfWeekName);
       Nclasses nclasses=new Nclasses();
       nclasses.setId(nclasses1.getId());
       nclasses.setStatus(1);

        boolean b=nclassesService.setqiandao(nclasses);
        if (b){
            new ObjectMapper().writeValue(response.getOutputStream(), Result.success("签到成功"));
        }
        new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("签到失败"));
    }
}
